﻿using System;
using System.Management.Automation;
using DotNet.DevOps.Tasks.AppConfig;
using DotNet.DevOps.Tasks.Log4Net;
using DotNet.DevOps.Tasks.Service;
using DotNet.DevOps.Tasks.Util;

namespace DotNet.DevOps.Tasks.Cmdlets
{
    /// <summary>
    /// Can stop a windows service on a local or remote machine.
    /// It is possible to define timeout for operation to complete.
    /// 
    /// Requirements:
    /// * The user under which the task is executed must have the correct rights to stop on the local/remote machine.
    /// 
    /// </summary>
    /// <example>
    /// import-module .\DotNet.DevOps.Tasks.dll
    /// 
    /// Stop-Service -Property @{
    ///                           Name="MyService" 
    ///                           Machine="TESTSERVER" 
    ///                           Timeout="30000"
    ///                         }
    /// </example>
    [Cmdlet(VerbsLifecycle.Stop, "Service", ConfirmImpact = ConfirmImpact.None, SupportsShouldProcess = false, SupportsTransactions = false)]
    public class Stop_Service : Cmdlet, IStopService
    {
        /// <summary>
        /// Name of the service to start.
        /// </summary>
        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public string Name { get; set; }

        /// <summary>
        /// Name of the machine on which to start the service. Default to this machine.
        /// </summary>
        [Parameter(Mandatory = false, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public string Machine { get; set; }

        /// <summary>
        /// Complete timeout, in milliseconds, for all the service command which might fire (Start). Default infinte.
        /// </summary>
        [Parameter(Mandatory = false, Position = 2, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        public int Timeout { get; set; }

        private StopService task;

        public Stop_Service()
        {
            task = new StopService(new PowershellCmdletLogger(this));
            Timeout = task.Timeout;
        }

        protected override void BeginProcessing()
        {
            task = new StopService(new PowershellCmdletLogger(this))
                .CopyPropertyValuesFrom(this) as StopService;
        }

        protected override void ProcessRecord()
        {
            task.Execute();
        }
    }
}
